import sys
import os
import urllib.request
import subprocess

# 版本映射表
VERSION_MAP = {
    "3.10": "cp310-cp310",
    "3.11": "cp311-cp311", 
    "3.12": "cp312-cp312"
}

BASE_URL = "https://github.com/Gourieff/Assets/raw/main/Insightface/insightface-0.7.3-{version}-win_amd64.whl"

def get_python_version():
    """获取Python版本号"""
    major = sys.version_info.major
    minor = sys.version_info.minor
    return f"{major}.{minor}"

def download_whl(version_tag):
    """下载对应版本的whl文件"""
    url = BASE_URL.format(version=version_tag)
    filename = url.split("/")[-1]
    
    print(f"[下载] 正在下载 {filename}...")
    urllib.request.urlretrieve(url, filename)
    return filename

def install_whl(filename):
    """安装whl文件"""
    print(f"[安装] 正在安装 {filename}...")
    result = subprocess.run([sys.executable, "-m", "pip", "install", filename], 
                          capture_output=True, text=True)
    
    if result.returncode == 0:
        print("[成功] 安装完成")
        os.remove(filename)  # 删除临时文件
    else:
        print(f"[错误] 安装失败: {result.stderr}")

def main():
    try:
        py_version = get_python_version()
        print(f"[检测] 当前Python版本: {py_version}")
        
        if py_version not in VERSION_MAP:
            raise ValueError(f"不支持Python {py_version}版本")
        version_tag = VERSION_MAP[py_version]
        whl_file = download_whl(version_tag)
        install_whl(whl_file)
        
    except Exception as e:
        print(f"[错误] 发生异常: {str(e)}")
        sys.exit(1)

if __name__ == "__main__":
    main()